package com.srwl.mytx.converter;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Helper;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.parse.UserProfileManager;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Converter;

public  class MyRequestBodyConverter<T> implements Converter<T, RequestBody> {

    private String TAG = "MyRequestBodyConverter";
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");


    public MyRequestBodyConverter() {

    }

    @Override
    public RequestBody convert(T value) throws IOException {

        //对post的body 进行包装，加上token 和时间戳
        JSONObject jsonObject;
        if (value instanceof JSONObject) {
            jsonObject = (JSONObject) value;//上传的数据类型是JSONObject，我们默认为里面是 已经包含了 token 字段，可能含有ct 字段，
//            if (!jsonObject.containsKey("token")) {
//                setToken(jsonObject);
//            }
        } else {
            jsonObject = new JSONObject();
            jsonObject.put("ct", value);
            setToken(jsonObject);
        }
        jsonObject.put("created", System.currentTimeMillis()+ MyApplication.timeOffset);//里面放入created 元素，标识此请求的时间，

//
//        JSONObject encrypt = new JSONObject();
//        try {
//            encrypt = HttpEncryptUtil.appEncrypt(jsonObject, servicePublicKey);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        //  Log.d(TAG,"加密后内容："+encrypt.toJSONString());
        byte[] content = jsonObject.toJSONString().getBytes();

        return RequestBody.create(MEDIA_TYPE, content);
    }

    private void setToken(JSONObject jsonObject) {
        String token = UserProfileManager.getInstance().getLoginUserInfo().getToken();
        if (!TextUtils.isEmpty(token)) {
            jsonObject.put("token", token);
        } else {
            Log.w(TAG, "convert: 没有获取到token");
        }
    }
}
